from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext import db

from nerd.web.environment import Environment 
from nerd.compute.constants import GetConstSplit, CheckConstValid 
from nerd.web.library import Library
import nerd.web
from nerd.modules import User_formulas, UserConstants, Notebooks, NotebooksConst
 
import os

 

class MainPage(webapp.RequestHandler):
    
    TITLE = "$ Talk Nerdy to Me..."
    SUBTITLE = "Welcome to my little nerd-mania...!"
    
    def login(self):
        return users.create_login_url(self.request.uri)
        
    def get(self):
        user = users.get_current_user()
        self.response.headers['Content-Type'] = 'text/html'
        raw = file(os.path.join(nerd.web.__path__[0], 'templates/portal.html'))\
            .read()
        fmtd = raw.replace("__user__", user and user.nickname() or 'guest')\
            .replace("__login__", self.login())
        self.response.out.write(fmtd)
        return
        
        if user:
            
            self.response.headers['Content-Type'] = 'text/html'
            self.response.out.write("<h1>%s</h1>" % self.TITLE)
            self.response.out.write("<h2>%s</h2>" % self.SUBTITLE)
            self.response.out.write("Hello, " + user.nickname())
            #l = Library(user)
            #e = Environment(l.get_formulas())
            self.response.out.write("""
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
              <script type="text/javascript"> 
                function OnShowClick(){
               window.location = "?notebook=" + $('#NotebookType').val();
                }
            </script>
              <form action="/sign1" method="post">
                <div><input type="entry" id="NotebookType" name="NotebookType" value="Enter Notebook Name" rows="1">
                <input type="button" name="ShowCurNotebook" onclick="OnShowClick()" value="show"</div>
                <div><input type="entry" name="content" rows="1"></div>
                <div><input type="submit" name="add" value="Add Formula">
                <input type="submit" name="const" value="Add Constant"></div>
              </form>""")  
            #self.response.out.write("<b>User Formulas</b>\n" + e.format_formulas())
            #ec = Environment(l.get_conste())
            #self.response.out.write("<b>User Constants</b>\n" + ec.format_formulas())  
            if (self.request.get("notebook")):
                notebook = self.request.get("notebook")
                l = Library(notebook=notebook )
                ec = Environment(l.get_notebook())
                self.response.out.write("<b>User Notebook Formulas</b>\n" + ec.format_formulas())
            
            ADD_BUTTON = \
            """
    <a href="http://www.google.com/ig/adde?moduleurl=__url__/nerd.xml"><img src="http://buttons.googlesyndication.com/fusion/add.gif" style="width:104px; height:17px;border:0px;" alt="Add to iGoogle" /></a>
            """
            ADD_BUTTON = ADD_BUTTON.replace("__url__", self.trim(self.request.url))
            self.response.out.write(ADD_BUTTON)
        else:
            self.redirect(users.create_login_url(self.request.uri))
        
    def trim(self, url):
        if url.endswith("/"):
            return url[:-1]
        else:
            return url
                
class FormulasWave(webapp.RequestHandler): 
    def get(self):
        user = users.get_current_user()
        user = user or "olga"
        if user:
            if self.request.get('const'):
                CheckConstValid(self.request.get('content'))
                user_formula = UserConstants()
                notebook = NotebooksConst()
                user_formula.user = users.get_current_user()
                user_formula.content = GetConstSplit(self.request.get('content'))[1]
                user_formula.name = GetConstSplit(self.request.get('content'))[0]
            else:
                user_formula = User_formulas()    
                notebook = Notebooks()
                user_formula.user = users.get_current_user()
                user_formula.content = self.request.get('content')
            db.put(user_formula)
            notebook.formulaID = user_formula
            notebook.nbID = notebook_id = self.request.get('NotebookType')
            db.put(notebook)
        else:
            self.redirect(users.create_login_url(self.request.uri))  
        if self.request.get('noredir'):
            self.redirect('/gadget?notebook=' + notebook_id)


class Formulas(webapp.RequestHandler): 
    def post(self):
        user = users.get_current_user()
        
        if self.request.get('kind') == 'constant':
            CheckConstValid(self.request.get('content'))
            user_formula = UserConstants()
            notebook = NotebooksConst()
            const_split = GetConstSplit(self.request.get('content'))
            user_formula.name = const_split[0]
            user_formula.content = const_split[1]
        else:
            user_formula = User_formulas()    
            notebook = Notebooks()
            user_formula.content = self.request.get('content')
        if user:
            user_formula.user = users.get_current_user()
        db.put(user_formula)
        notebook.formulaID = user_formula
        notebook.nbID = self.request.get('notebook')
        db.put(notebook)
        self.response.out.write(user_formula.key());
        
class FavFormulas(webapp.RequestHandler):
        def get(self):
            notebook = str(users.get_current_user()) + ":FavoriteForm"
            l = Library(notebook=notebook)
            ec = Environment(l.get_notebook())
            self.response.out.write(ec._js())
            self.response.out.write(ec.format_formulas_brief())
            ec.on_click_operation = "toggle_edit"
            self.response.out.write("""
                <form action="/sign" method="post">
                <input type="hidden" name="NotebookType" value="%(notebook)s"
                </form>"""%{"notebook":notebook})                      

class FavConst(webapp.RequestHandler):
        def get(self):
            notebook = str(users.get_current_user()) + ":FavoriteConst"
            l = Library(notebook=notebook)
            ec = Environment(l.get_notebook())
            self.response.out.write(ec._js())
            self.response.out.write(ec.format_formulas_brief())
            ec.on_click_operation = "toggle_edit"
            self.response.out.write("""
                <form action="/sign" method="post">
                <input type="hidden" name="NotebookType" value="%(notebook)s"
                </form>"""%{"notebook":notebook}) 

class FormulaUpdate(webapp.RequestHandler):
    def post(self):
        dataobj = Library('').update(self.request.get("kind"),
                                     self.request.get("key"),
                                     self.request.get("content"))
        notebook = self.request.get("notebook")
        if notebook:
            self.redirect("/gadget?notebook=" + notebook)
        elif dataobj is not None:
            e = Environment([dataobj])
            self.response.out.write(e.formulas[0].brief());


class ListNotebook(webapp.RequestHandler):
    
    def get(self):
        notebook = self.request.get("notebook")
        if not notebook: notebook = "myfav";
        l = Library(notebook=notebook)
        ec = Environment(l.get_notebook(), notebook_id=notebook)
        self.response.out.write(ec.list_formulas())


class ListNotebooks(webapp.RequestHandler):
    
    def get(self):
        user = users.get_current_user()
        if 1: #user:
            l = Library(user=user)
            self.response.out.write(self.make_ul(l.get_notebooks()))
        else:
            self.response.out.write("To view your notebooks, please log in.")
            
    def make_ul(self, strings):
        return "<ul>%s</ul>" % ("".join("<li>%s</li>" % x for x in strings))


class WaveGadget(webapp.RequestHandler):
    
    def get(self):
        notebook = self.request.get("notebook")
        if (notebook == ''):
            notebook = str(users.get_current_user()) + ":FavoriteConst" 
        l = Library(notebook=notebook )
        ec = Environment(l.get_notebook(), notebook_id=notebook)
        self.response.out.write(ec._js())
        self.response.out.write(ec.format_formulas_brief())
        ec.on_click_operation = "toggle_edit"
        

        
class WaveGadgetFile(webapp.RequestHandler):
    
    def get(self):
        path = self.request.path
        if path.endswith(".xml"):
            self.response.headers['Content-Type'] = 'application/xml'
        xml = file(nerd.__path__[0] + "/gadget" + path).read()
        if self.request.get("hostname"):
            url = "http://" + self.request.get("hostname")
        else:
            url = self.request.host_url
        xml = xml.replace("__url__", url)
        self.response.out.write(xml)
        

class ResourceFile(webapp.RequestHandler):

    @classmethod
    def resource_file(cls, path):
        if path.startswith("/"): path = path[1:]
        return os.path.join(nerd.web.__path__[0], path)

    def get(self):
        path = self.request.path
        raw = file(self.resource_file(path)).read()
        if path.endswith(".gif"):
            self.response.headers['Content-Type'] = 'image/gif'
        elif path.endswith(".png"):
            self.response.headers['Content-Type'] = 'image/png'
        else:
            url = self.request.host_url
            raw = raw.replace("__url__", url)
            user = users.get_current_user()
            raw = raw.replace("__user__", user and user.nickname() or "guest")
        self.response.out.write(raw)
        

class Plot(webapp.RequestHandler):
    
    def get(self):
        formula = self.request.get("f")
        self.response.headers['Content-Type'] = 'text/html'
        self.response.out.write(nerd.modules.GetPlot(formula))


class ResearchWikipedia(webapp.RequestHandler):
    
    def get(self):
        from nerd.web.data_mining.wikipedia import WikipediaMining
        import cgi
        search = self.request.get("search")
        wikipedia = WikipediaMining()
        data = wikipedia.harvest_math(search)
        for article, formulas in data:
            formulas = [f for f in formulas if not self.boring(f)]
            if len(formulas) > 0:
                self.response.out.write("<h1>%s</h1>" % cgi.escape(article))
                for latex in formulas:
                    self.response.out.write("<p>%s</p>" % cgi.escape(latex))
                    
    def boring(self, latex):
        return latex.isalnum() or len(latex) < 10



switch = \
     [('/', MainPage),
      ('/gadget', WaveGadget),
      ('/nerd.xml', WaveGadgetFile),
      ('/nerd.js', WaveGadgetFile),
      ('/px/.*', ResourceFile),
      ('/templates/.*', ResourceFile),
      ('/lib/.*', ResourceFile),
      ('/sign', FormulasWave),
      ('/sign1', Formulas),
      ('/list', ListNotebook),
      ('/notebooks', ListNotebooks),
      ('/favformulas', FavFormulas),
      ('/favconst', FavConst),
      ('/update', FormulaUpdate),
      ('/plot', Plot),
      ('/research/wiki', ResearchWikipedia)]

application = webapp.WSGIApplication(switch,
                                     debug=True)



def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
